package com.leetcode.multithreading.anyan;

public class Jm_Gun {
    private int count = 0;

    public synchronized void shangTang() throws Exception {
        while (count >= 20) {
            System.out.println("子弹装满");
            wait();
        }
        count++;
        System.out.println("子弹+1,子弹数量：" + count + ",当前线程：" + Thread.currentThread().getName());
        notifyAll();
    }
    public synchronized void sheji() throws Exception {
        while (count == 0) {
            System.out.println("子弹打完");
            wait();
        }
        count--;
        System.out.println("子弹-1,子弹数量：" + count + ",当前线程：" + Thread.currentThread().getName());
        notifyAll();
    }

    public static class Product implements Runnable {
        Jm_Gun jg;
        Product(Jm_Gun jg) {
            this.jg = jg;
        }
        @Override
        public void run() {
            while (true) {
                try {
                    jg.shangTang();
                    Thread.sleep(1);//注意观察这里睡眠和不睡眠的现象
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class Customer implements Runnable {
        Jm_Gun jg;
        Customer(Jm_Gun jg) {
            this.jg = jg;
        }
        @Override
        public void run() {
            while (true) {
                try {
                    jg.sheji();
                    Thread.sleep(1);//注意观察这里睡眠和不睡眠的现象
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Jm_Gun gun = new Jm_Gun();
        for (int i = 0; i < 10; i++) {
            new Thread(new Product(gun)).start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(new Customer(gun)).start();
        }
//        Thread thread1 = new Thread(new Product(gun));
//        thread1.start();
//        Thread thread2 = new Thread(new Customer(gun));
//        thread2.start();
    }

}
